<?php

namespace app\api\controller;
use think\Db;
use app\common\model\Travel as TravelModel;
/**
 * 用户api接口
 */
class Cron 
{
    /**
     * 获取环信聊天记录
     */
    public function chat_history()
    {
        $list = getChatHistory();
        foreach($list as $value)
        {
           $chat = Db::name('chat')->where('msg_id',$value['msg_id'])->find();
           // 根据 msg_id判断此聊天记录是否存在，如果存在不插入，存在则插入数据库
           if(!$chat)
           {
              $value['payload'] = json_encode($value['payload'],JSON_UNESCAPED_UNICODE);
              Db::name('chat')->insert($value);
              Log::info('聊天记录', $value['msg_id'].'插入成功');
           }
        }
    }

    // 过期的广告下架
    public function ad()
    {
       $adList = Db::name('advertisement')->where(['status'=>'normal'])->select();
       foreach ($adList as $k => $v) {
          if(strtotime($v['endtime']) < time())
          {
             Db::name('advertisement')->where(['id'=>$v['id']])->update(['status'=>'hidden']);
          }
       }
    }

    // 活动结束 分销
    public function distribution()
    {
      // 报名中的活动 
      $list = model('Travel')->where(['state'=>2])->whereTime('endtime', '<', time())->select();
      foreach ($list as $k => $v) {
         // 活动活动报名人数
          $count = model('TravelMember')->where(['travel_id'=>$v])->count();
          if($count < $v['group_num'])
          {
            $travelMembers = model('TravelMember')->where(['travel_id'=>$v['id'],'paid'=>1])->select();
            foreach ($travelMembers as $key => $value) {
                $order = model('Order')->where(['type'=>1,'good_id'=>$value['id']])->find();
                action('Pay/refund', ['order_id'=>$order['id']]);
            }
            // 未达到成团人数  活动自动取消 退还会员报名费
           model('Travel')->save(['state'=>5],['id'=>$v['id']]);
          }
          else
          {
             // 设置s活动为已结束 
             if(model('Travel')->save(['state'=>3],['id'=>$v['id']]))
             {
               // 获取发布活动人的信息
                $sponsor = model('User')->get($v['sponsor']);
                //总利润
                $total = $count * $v['memebr_price'] - $v['cost'];

                //计算佣金 总利润的70% * 20% / 最多限制人数
                $commission = ($total * 0.7) * 0.2 / $v['limit_num'];

                // role： 1 社群；2 用户
                switch ($sponsor['role']) {
                  case '1':
                        if($v['type'] == 0)
                        {
                            // 国内活动
                            //1、 分销给供应商 钱包
                            $travel = TravelModel::with('activity')->where(['id'=>$travel_id])->find();
                            foreach ($travel['activity'] as $ak => $av) {
                              $supplier = model('supplier')->get($av['supplier_id']);
                             // $time = "(".date('Y/m',$av['pivot']['begintime']."-".date('Y/m',$av['pivot']['endtime'].")";
                              $title = "活动名称";
                              if($supplier['type'] == 1)
                              {
                                  $title = "活动场地";
                              }
                              // type  用户类型：1 供应商；2 社群用户
                              // mode  0 收入；1 支出
                              // paylog($type,$user_id,$title,$content,$mode)
                              paylog(1,$supplier['id'],$title,$travel['titles'],0,$ac['fee']);

                              model('User')->where(['id'=>$supplier['id']])->setInc('sum_income',$av['fee']);//总收入
                              model('User')->where(['id'=>$supplier['id']])->setInc('wallet_money',$av['fee']);// 账户余额
                              model('User')->where(['id'=>$supplier['id']])->setInc('activity_income',$av['fee']);// 活动收入
 

                              // 5、退还活动定金
                              $order_id = model('Order')->where(['type'=>4,'good_id'=>$v['id']])->value('id');
                              action('Pay/refund', ['order_id'=>$order_id]);
                            }
                        }
                       
                        // 2、 各个用户的佣金（总利润的70% * 20% / 最多限制人数）
                        $travelMembers = model('TravelMember')->field('parentid,count(*) as num')->group('parentid')->where('parentid','<>',0)->select();
                        $sum_commission = 0;
                        foreach ($travelMembers as $mk => $mv) {
                          paylog(2,$mv['parentid'],'分销报名佣金',$travel['titles'],0,$commission * $mv['num']);
                          $sum_commission += $sum_commission;

                           // 用户总收入增加
                          model('User')->where(['id'=>$mv['parentid']])->setInc('sum_income',$commission * $mv['num']);
                           // 用户的电子钱包增加
                          model('User')->where(['id'=>$mv['parentid']])->setInc('wallet_money',$commission * $mv['num']);
                           // 用户活动收入增加
                          model('User')->where(['id'=>$mv['parentid']])->setInc('activity_income',$commission * $mv['num']);
                        }

                        // 3、 社群毛利（总利润的70% - 用户佣金）
                        paylog(2,$sponsor['id'],'活动赚取金额',$travel['titles'],0,$total - $sum_commission);
                        // 用户的电子钱包，总收入增加
                        model('User')->where(['id'=>$sponsor['id']])->setInc('sum_income',$total - $sum_commission);
                        // 用户的电子钱包增加
                        model('User')->where(['id'=>$sponsor['id']])->setInc('wallet_money',$total - $sum_commission);
                        // 用户的电子钱包，活动收入增加
                        model('User')->where(['id'=>$sponsor['id']])->setInc('activity_income',$total - $sum_commission);

                        // 4、 平台收取的服务费

                        // 5、 退还活动定金
                    break;
                  default:
                    # 默认用户
                    // 1、转账给供应商
                    // 2、退还活动定金
                        $travel = TravelModel::with('activity')->where(['id'=>$travel_id])->find();
                        foreach ($travel['activity'] as $ak => $av) {
                          $supplier = model('supplier')->get($av['supplier_id']);
                          paylog(1,$supplier['id'],$title,$travel['titles'],0,$ac['fee']);

                          model('User')->where(['id'=>$supplier['id']])->setInc('sum_income',$av['fee']);//总收入
                          model('User')->where(['id'=>$supplier['id']])->setInc('wallet_money',$av['fee']);// 账户余额
                          model('User')->where(['id'=>$supplier['id']])->setInc('activity_income',$av['fee']);// 活动收入


                          // 5、退还活动定金
                          $order_id = model('Order')->where(['type'=>4,'good_id'=>$v['id']])->value('id');
                          action('Pay/refund', ['order_id'=>$order_id]);
                        }
                    break;
                }
             }
          }
      }
    }
}
